#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64

import requests
from loguru import logger

from apps.pdd.pdd.mms import gen_anti_content
from apps.pdd.pdd.utils.pdd_verify import PddSliderVerify
from components.config import WFQ_SOURCE_MYSQL_CONFIG
from utils.db.mysqldb import MysqlDB


class MmsCertificate:
    session = requests.session()

    def __init__(self, cookies=None, proxy=None):
        headers = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "origin": "https://pifa.pinduoduo.com",
            "pragma": "no-cache",
            "priority": "u=1, i",
            "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
        }
        self.session.headers = headers
        if cookies:
            self.session.cookies.update(cookies)
        if proxy:
            self.session.proxies = proxy
        self._to_db = None

    @property
    def to_db(self):
        if self._to_db is None:
            self._to_db = MysqlDB(
                ip=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_IP"],
                port=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_PORT"],
                db=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_DB"],
                user_name=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_USER_NAME"],
                user_pass=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_USER_PASS"],
            )
        return self._to_db

    def query_mall_info(self, mall_id_encrypt, verify_auth_token=None):
        """
        {"success":true,"errorCode":1000000,"errorMsg":null,"result":{"mallId":"kSXYIuY-V3tjVERfCeVGhw","mallName":"位名数码专营店","mallLogo":"http://t16img.yangkeduo.com/pdd_ims/img_check/v2/E6EDFF2D6EE40720200112161559105/c238bcb84d6d409d9fd32cf998fac33d.png","salesTip":"已售：136件","mallStar":4.0,"mallDesc":"该商户暂未上传店铺简介","mallPageHeadShowTags":[{"showTagType":2,"desc":"顺丰包邮","backgroundColor":"#15E02E24","scriptColor":"#FFE02E24","transparentDegree":"0.08","avatars":null}],"mallPageServiceLabels":[{"tagType":2,"labelSn":"hive-130001","showText":"顺丰包邮","showDetail":"商家承诺指定区域\"顺丰包邮\"，未履行服务将赔付15元无门槛代金券","backgroundColor":"#15E02E24","scriptColor":"#FFE02E24","transparentDegree":"0.08"},{"tagType":2,"labelSn":"hive-130007","showText":"分期付款","showDetail":"消费者购买商品时，可分期付款","backgroundColor":"#15E02E24","scriptColor":"#FFE02E24","transparentDegree":"0.08"},{"tagType":2,"labelSn":"hive-130002","showText":"7天无理由退货","showDetail":"满足相应条件时，消费者可申请\"7天无理由退货\"","backgroundColor":"#15E02E24","scriptColor":"#FFE02E24","transparentDegree":"0.08"},{"tagType":2,"labelSn":"hive-140010","showText":"48小时发货","showDetail":"若商品支持该项服务，商家未在48小时内发货，消费者将会收到至少3元无门槛代金券","backgroundColor":"#15E02E24","scriptColor":"#FFE02E24","transparentDegree":"0.08"}],"mallLicenceCertificate":{"mallName":"位名数码专营店","showIcon":true,"isCertificated":true,"mallPublicityDocument":"","title":"拼多多网店经营者证照信息","mallBusinessLicenceInfo":{"businessLicenceUrl":"","businessLicenceTitle":"根据相关法律法规要求对网店营业执照信息公示如下:","businessLicenceNote":"注：以上营业执照信息来源于卖家自行申报及工商系统数据，具体以工商部门登记为准。经营者需确保信息真实有效，平台也将定期核查。如与实际不符，为避免违规，请联系当地工商部门或平台客服更新。"},"mallCertificateInfoList":[]}}}
        """
        url = "https://pifa.pinduoduo.com/pifa/supplier/queryMallInfo"
        data = {"mallId": mall_id_encrypt}
        self.session.headers.update(
            {
                "Anti-Content": gen_anti_content(),
            }
        )
        if verify_auth_token:
            self.session.headers.update(
                {
                    "verifyauthtoken": verify_auth_token,
                }
            )
        response = self.session.post(url, json=data)
        resp = response.json()
        logger.info(f"查询商户信息结果：{resp}")
        error_code = resp.get("error_code") or resp.get("errorCode")
        if error_code == 54001:
            verify_auth_token = resp["result"]["verifyAuthToken"]
            verify_res = PddSliderVerify(verify_auth_token).run()
            if verify_res:
                return self.query_mall_info(mall_id_encrypt, verify_auth_token=verify_auth_token)
            else:
                raise Exception("查询商户信息结果 验证失败")
        if error_code != 1000000:
            raise Exception(f"查询商户信息失败：{resp}")
        else:
            mall_licence_certificate = resp["result"]["mallLicenceCertificate"]
            is_certificated = mall_licence_certificate["isCertificated"]
            return is_certificated

    def query_mall_licence_certificate(self, mall_id_encrypt, verify_auth_token=None, mall_id=None):
        logger.info(f"查询证照：{mall_id_encrypt} {verify_auth_token}")
        url = "https://pifa.pinduoduo.com/pifa/supplier/queryMallLicenceCertificate"
        self.session.headers.update(
            {
                "Anti-Content": gen_anti_content(),
            }
        )
        if verify_auth_token:
            self.session.headers.update(
                {
                    "verifyauthtoken": verify_auth_token,
                }
            )
        data = {"mallId": mall_id_encrypt}
        response = self.session.post(url, json=data)
        resp = response.json()
        logger.debug(f"查询证照结果：{resp}")
        error_code = resp.get("error_code") or resp.get("errorCode")
        if error_code == 54001:
            verify_auth_token = resp["result"]["verifyAuthToken"]
            verify_res = PddSliderVerify(verify_auth_token).run()
            if verify_res:
                return self.query_mall_licence_certificate(mall_id_encrypt, verify_auth_token, mall_id=mall_id)
            else:
                raise Exception("验证失败")
        if error_code != 1000000:
            raise Exception(f"查询证照失败：{resp}")
        self.save_data(resp, mall_id_encrypt, mall_id=mall_id)
        return resp

    def save_data(self, response, mall_id_encrypt, mall_id=None):
        is_certificated = response["result"]["isCertificated"]
        mall_business_licence_info = response["result"]["mallBusinessLicenceInfo"]
        mall_name = response["result"]["mallName"]
        if is_certificated:
            save_item = {
                "mall_id_encrypt": mall_id_encrypt,
                "mall_name": mall_name,
                "business_licence_url": mall_business_licence_info["businessLicenceUrl"],
                "image_uuid": mall_business_licence_info["businessLicenceUrl"]
                .split("?")[0]
                .split("/water-mark-permanent/")[-1],
            }
            update_columns = [
                "mall_id_encrypt",
                "mall_name",
                "business_licence_url",
            ]
            if mall_id:
                save_item["mall_id"] = mall_id
                update_columns.append("mall_id")
            self.to_db.add_smart("source_pdd_mall_licence_certificate", save_item, update_columns=update_columns)
            try:
                content = requests.get(
                    save_item["business_licence_url"],
                    headers={
                        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
                        "accept-language": "zh-CN,zh;q=0.9",
                        "cache-control": "no-cache",
                        "pragma": "no-cache",
                        "priority": "u=0, i",
                        "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
                        "sec-ch-ua-mobile": "?0",
                        "sec-ch-ua-platform": '"Windows"',
                        "sec-fetch-dest": "document",
                        "sec-fetch-mode": "navigate",
                        "sec-fetch-site": "none",
                        "sec-fetch-user": "?1",
                        "upgrade-insecure-requests": "1",
                        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
                    },
                ).content
                save_item["base64_data"] = base64.b64encode(content).decode()
                self.to_db.add_smart("source_pdd_mall_licence_certificate", save_item, update_columns=["base64_data"])
            except Exception as e:
                print(e)
            logger.success(f"保存证照成功：{mall_name} {mall_id_encrypt}")
            if mall_id:
                self.to_db.add_batch_smart(
                    "zm_pdd_mall_id",
                    [
                        {
                            "mall_id": mall_id,
                            "is_certificated": 1,
                        }
                    ],
                    update_columns=["is_certificated"],
                )
        else:
            print(f"{mall_name}未授权")

    def run(self, mall_id_encrypt, mall_id=None):
        is_certificated = self.query_mall_info(mall_id_encrypt)
        if is_certificated is False:
            logger.warning(f"查询商户信息结果：未授权证照 {mall_id_encrypt} {is_certificated}")
            if mall_id:
                self.to_db.add_batch_smart(
                    "zm_pdd_mall_id",
                    [
                        {
                            "mall_id": mall_id,
                            "is_certificated": 0,
                        }
                    ],
                    update_columns=["is_certificated"],
                )
        else:
            self.query_mall_licence_certificate(mall_id_encrypt, mall_id=mall_id)


if __name__ == "__main__":
    cookies = {
        "_nano_fp": "XpmyXq9Jn0PxX0dxl9_hqymebVpva6Sh4PaX3AVf",
        "webp": "true",
        "VISITOR_PASS_ID": "zjBUTyTpRdgsCBia5ScbinF8DEzfoPNRo5anD7QrZ7IxgPegnRuCSOaAqVa7k9xvuX8f7xBUHv1UuMAExDGEXfd1hUeETNEPwPSNtsL1360_103edfe74db",
        "api_uid": "CiDtc2iLWvKt/ACobxw2Ag==",
        "rckk": "0KnmGQbIBxM965CND9n283P3xPfBzfER",
        "_bee": "0KnmGQbIBxM965CND9n283P3xPfBzfER",
        "ru1k": "f4f488d4-f4cc-4579-99c2-c8af6fe16c21",
        "_f77": "f4f488d4-f4cc-4579-99c2-c8af6fe16c21",
        "ru2k": "15ca269b-5d9d-44dd-852d-646c2225b362",
        "_a42": "15ca269b-5d9d-44dd-852d-646c2225b362",
        "SUB_PASS_ID": "eyJ0IjoiRmFXeXVSSHI5WEcxZjdTbkI5TURBd3l1ZmxHQi95cm5UVkRPbG9CSldGamlXcjdjaTlxRWpubzFJQm5YTzJLdiIsInYiOjEsInMiOjE0LCJtIjo2NzQxMTAwODcsInUiOjE2OTgwOTI3NX0",
    }
    test = MmsCertificate(
        cookies,
        proxy={
            # "http": "http://127.0.0.1:7890",
            # "https": "http://127.0.0.1:7890",
        },
    )
    test.query_mall_licence_certificate("OZTqaYjCaSt7D9fPJd-lGA")
